<template>
	<view>
		<view v-if="list.length>0">
			<scroll-view scroll-y="true" 
			style="position: absolute;left: 0;top: 0;right: 0;bottom: 100rpx;" 
			:scroll-into-view="scrollInto" scroll-with-animation>
				<block v-for="(item,index) in list" :key="index">
					<view :id="'chat'+index">
						<user-chat-list 
						:item="item" 
						:index="index" 
						:pretime="index > 0 ? list[index-1].create_date : 0">
						</user-chat-list>
					</view>
				</block>
				
			</scroll-view>
		</view>
		<bottom-input @submit="submit"></bottom-input>
	</view>
</template>

<script>
	import userChatList from '@/components/user-chat/user-chat-list'
	import bottomInput from '@/components/common/bottom-input'
	import {getDetailNews,getNewsAdd} from "@/network/news.js";
	export default {
		components:{
			userChatList,
			bottomInput
		},
		destroyed() {
			this.$store.dispatch("closeSocketDetail")
			uni.$off('UserChat')
		},
		onBackPress() {
			uni.$emit("UserBack",this.list.slice(-1)[0])
		},
		onNavigationBarButtonTap(e){
			switch (e.index){
				case 0: // 左边
					console.log(this.list.slice(-1)[0])
					uni.navigateTo({
						url:"/pages/user-list/user-list"
					})
				break;	
			}
		},
		created() {
			uni.$on("UserChat",(res)=>{
				if(res.code==200){
					console.log(res)
					return
				}
				if(res.code ==201){
					this.list.push(res)
					this.pageToBottom()
					return
				}
			})
		},
		onLoad(e) {
			// 这里是聊天页
			this.uid = JSON.parse(e.user)

			this.$store.dispatch("openSocketDetail",this.uid)
			getDetailNews(this.uid).then(attr=>{
				let[err,res] = attr
				this.list = res.data
				uni.setNavigationBarTitle({
					title:e.username
				})
				this.$store.dispatch("totalNoread")
			})
			
		},
		onReady() {
			this.pageToBottom()
		},
		data() {
			return {
				uid:0,
				list:[],
				scrollInto:"",
				SocketTask:false
			}
		},
		methods:{
			submit(e){
				let userinfo = this.$store.state.userInfo
				let data = {
					code:201,
					user:userinfo.id,
					receive_user:this.uid,
					avatar:userinfo.avatar,
					username:userinfo.username,
					content:e,
					type:1,
					create_date:new Date().getTime()
				}
				this.list.push(data)
				this.$store.dispatch("SendSocketDetail",data)
				this.pageToBottom()
			},
			// 滚动到底部
			pageToBottom(){
				let lastIndex = this.list.length - 1
				if(lastIndex<0) return
				this.$nextTick(function() {
						this.scrollInto = 'chat' + lastIndex
				});
				
			}
		}
	}
</script>

<style>

</style>
